﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenGado.Business;
using OpenGado.DATA;
using OpenGado.DATA.Entities;

namespace OpenGado.Win
{
    public partial class frmRequestItem : Form
    {
        public frmRequestItem()
        {
            InitializeComponent();
        }

        private void frmRequestItem_Load(object sender, EventArgs e)
        {

        }

        private void GetProducts()
        {
            Cursor.Current = Cursors.WaitCursor;
            cboProduct.Refresh();
            IList<Product> productList = ProductDataControl.Instance.Query("Project", cboProject.Text);

            //cboProduct.Text = ""; // clear off previous text if any 

            cboProduct.DataSource = productList;
            cboProduct.DisplayMember = "ProductName";

            Cursor.Current = Cursors.Default;
        }

        /// <summary>
        /// Binds projects to the list
        /// </summary>
        private void GetProjects()
        {
            cboProject.DataSource = ProjectDataControl.Instance.GetAllProjects();
            cboProject.DisplayMember = "Name";
        }

        /// <summary>
        /// Checkes if product is already existing in the grid
        /// </summary>
        /// <param name="idToCheck"></param>
        /// <returns> -1 if nothing  isfound and row index if product is found</returns>
        private int productExists(int idToCheck)
        {
            int exists = -1;

            if (dgvRequest.Rows.Count == 1)
            {
                return exists;
            }
            foreach (DataGridViewRow rw in dgvRequest.Rows)
            {
                if (rw.Cells[2].Value == null)
                {
                    break;
                }
                else if (idToCheck == (int)rw.Cells[2].Value)
                {
                    exists = rw.Index;
                    break;
                }


            }

            return exists;
        }

        private void ItemNewDataRow()
        {

            // check if already in the list
            int productRowIndex = productExists(GetSelectedProduct().Productid);
            Decimal quantity;
            Decimal subTotal;


            if (productRowIndex == -1)
            {
                // add a new line 
                DataGridViewRow rw = new DataGridViewRow();
                int n = dgvRequest.Rows.Add(rw);

                dgvRequest.Rows[n].Cells[0].Value = txtRequestId.Text;
                dgvRequest.Rows[n].Tag = GetSelectedProduct();
                dgvRequest.Rows[n].Cells[2].Value = GetSelectedProduct().Productid;
                dgvRequest.Rows[n].Cells[3].Value = GetSelectedProduct().ProductName;
                dgvRequest.Rows[n].Cells[4].Value = txtQuantity.Text;
                dgvRequest.Rows[n].Cells[5].Value = GetSelectedProduct().Sku;
                dgvRequest.Rows[n].Cells[6].Value = GetSelectedProduct().Storage.StoreName;
                dgvRequest.Rows[n].Cells[7].Value = GetSelectedProduct().CurrentPrice;

                // calculate sub total 

                calculateSubTotals();
            }
            else
            {
                Decimal newQuantity;
                Decimal oldQuantity;
                Decimal currentQuantity;

                Decimal.TryParse(txtQuantity.Text, out currentQuantity);

                decimal.TryParse(dgvRequest.Rows[productRowIndex].Cells[4].Value.ToString(), out oldQuantity);


                newQuantity = oldQuantity + currentQuantity;

                dgvRequest.Rows[productRowIndex].Cells[4].Value = newQuantity;
                calculateSubTotals();
                dgvRequest.Refresh();
            }


        }

        private void calculateSubTotals()
        {
            Decimal quantity;
            Decimal price;
            Decimal subTotal;

            foreach (DataGridViewRow rw in dgvRequest.Rows)
            {
                if (rw.Cells[4].Value != null)
                {
                    Decimal.TryParse(rw.Cells[4].Value.ToString(), out quantity);
                    Decimal.TryParse(rw.Cells[7].Value.ToString(), out price);
                    subTotal = quantity * price;
                    rw.Cells[8].Value = subTotal;
                }


            }

            txtTotal.Text = CalculateTotalValue().ToString();
        }

        private void PopulateDataGrid()
        {
            IList<Product> productList = ProductDataControl.Instance.GetAll();

            dgvRequest.DataSource = productList;

            dgvRequest.Columns[1].DataPropertyName = "ProductName";
        }

        private Product GetSelectedProduct()
        {
            Product p = (Product)cboProduct.SelectedItem;

            return p;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (ConsistencyCheckPassed())
            {
                ItemNewDataRow();
            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private Decimal CalculateTotalValue()
        {
            Decimal itemValue;
            Decimal runningValue = 0; //initial value
            foreach (DataGridViewRow rw in dgvRequest.Rows)
            {
                if (rw.Cells[8].Value == null)
                {
                    break;
                }
                Decimal.TryParse(rw.Cells[8].Value.ToString(), out itemValue);
                runningValue += itemValue;
            }

            return runningValue;
        }

        private List<int> GetSelectedRows()
        {
            List<int> selectedRows = new List<int>();
            foreach (DataGridViewRow rw in dgvRequest.SelectedRows)
            {
                selectedRows.Add(rw.Index);
            }

            return selectedRows;
        }

        /// <summary>
        /// Removes selected rows from the list
        /// </summary>
        private void RemoveRows()
        {
            foreach (DataGridViewRow rw in dgvRequest.SelectedRows)
            {
                if (rw != null)
                {
                    dgvRequest.Rows.Remove(rw);
                }

            }
            // we need to recalculate the order value again.
            CalculateTotalValue();
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {

            DialogResult res;

            res = MessageBox.Show("Are you sure you want to remove selected item(s)? ", "Inventory", MessageBoxButtons.YesNo);
            if (res == DialogResult.Yes)
            {
                RemoveRows();
            }

        }
        /// <summary>
        /// Checks the submitted data for consistency
        /// </summary>
        private bool ConsistencyCheckPassed()
        {
            bool pass = true;
            Decimal quantity;
            Decimal.TryParse(txtQuantity.Text, out quantity);
            ep.Clear();

            if (quantity == 0)
            {
                pass = false;
                ep.SetError(txtQuantity, "Quantity has to be numeric and can't be 0");
            }
            else if (String.IsNullOrEmpty(txtIssueTo.Text))
            {
                pass = false;
                ep.SetError(txtIssueTo, "Required Value");
            }
          
            else if (cboProduct.SelectedItem == null)
            {
                pass = false;
                ep.SetError(cboProduct, "Select a product from the list");
            }


            return pass;
        }

        private void cboProduct_DropDown(object sender, EventArgs e)
        {
            // make sure project is selected 
            ep.Clear();

            if (!string.IsNullOrEmpty(cboProject.Text))
            {
                GetProducts();
            }
            else
            {
                ep.SetError(cboProject, "Select Project");
            }

        }


        /// <summary>
        /// will issue items on the grid once clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnIssue_Click(object sender, EventArgs e)
        {
            Issue();
            MessageBox.Show("Items Requested,  Store has been informed", "Inventory", MessageBoxButtons.OK);
            //Todo: print out the list after issue. 
        }

        /// <summary>
        ///  Issues items on the page. 
        /// </summary>
        private void Issue()
        {
            if (dgvRequest.Rows.Count > 1)
            {
                IssueItemHeader header = new IssueItemHeader();

                header.IssueDate = dtpIssueDate.Value;
                header.IssueTo = txtIssueTo.Text;
                header.IssueStamp = DateTime.Now;
                header.IssueComment = txtRemarks.Text;

                List<IssueItem> itemList = new List<IssueItem>();

                // check the grid and add to issue list 
                Decimal quantity;

                foreach (DataGridViewRow rw in dgvRequest.Rows)
                {
                    if (rw.Tag == null) break;

                    IssueItem issueItem = new IssueItem();
                    issueItem.IssueItemHeader = header;
                    Decimal.TryParse(rw.Cells[4].Value.ToString(), out quantity);
                    issueItem.IssueQuantity = quantity;
                    issueItem.Product = (Product)rw.Tag;
                    itemList.Add(issueItem);
                }

                //ProductBusiness pb = new ProductBusiness();
                //pb.IssueProducts(header, itemList);
            }
        }


    }
}
